package com.runnor.common.websys.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runnor.common.websys.system.entity.ApiResult;
import com.runnor.common.websys.system.entity.SysMenu;
import com.runnor.common.websys.system.entity.bo.SysMenuBo;
import com.runnor.common.websys.system.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/sysmenu")
public class SysMenuController {

    @Autowired
    SysMenuService sysMenuService;

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('menu:list')")
    public ResponseEntity page(@RequestParam(defaultValue = "1") Integer current,
                               @RequestParam(defaultValue = "10") Integer size,
                               SysMenu sysMenu) {

        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();

        queryWrapper
                .like(StringUtils.hasText(sysMenu.getName()), "name", sysMenu.getName())
                .eq("type", "菜单")
                .and(StringUtils.hasText(sysMenu.getParentNo()), w -> {
                    w.eq("parent_no", sysMenu.getParentNo()).or().eq("no", sysMenu.getParentNo());
                })
                .like(StringUtils.hasText(sysMenu.getPermission()), "permission", sysMenu.getPermission())
                .eq(sysMenu.getEnable() != null, "enable", sysMenu.getEnable())
                .eq("deleted", 0)
                .orderByAsc("sort").orderByDesc("create_time");

        Page<SysMenuBo> data = sysMenuService.pages(new Page(current, size), queryWrapper);
        if (data.getRecords().size() > 0) {
            QueryWrapper<SysMenu> funcWrapper = new QueryWrapper<>();
            funcWrapper.lambda().eq(SysMenu::getType, "功能").in(SysMenu::getParentNo, data.getRecords().stream().map(r -> r.getNo()).collect(Collectors.toList())).orderByAsc(SysMenu::getSort);
            List<SysMenu> list = sysMenuService.list(funcWrapper);
            data.getRecords().forEach(record -> record.setChildren(list.stream().filter(l -> StrUtil.equals(l.getParentNo(), record.getNo())).map(e -> e.setParentName(record.getName())).collect(Collectors.toList())));
        }
        return ResponseEntity.ok(ApiResult.ok(data));
    }

    /**
     * 根据id查询角色
     */
    @GetMapping("/getById")
    public ResponseEntity getById(String no) {
        SysMenu sysMenu = sysMenuService.getById(no);
        return ResponseEntity.ok(ApiResult.ok(sysMenu));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('menu:add')")
    public ResponseEntity save(SysMenu sysMenu) {
        boolean save = sysMenuService.save(sysMenu);
        return ResponseEntity.ok(ApiResult.ok(save));
    }

    /**
     * 修改
     */
    @PostMapping("/updateById")
    @PreAuthorize("hasAuthority('menu:edit')")
    public ResponseEntity updateById(SysMenu sysMenu) {
        boolean save = sysMenuService.updateById(sysMenu);
        return ResponseEntity.ok(ApiResult.ok(save));
    }

    /**
     * 删除
     */
    @GetMapping("/deletes")
    @PreAuthorize("hasAuthority('menu:del')")
    public ResponseEntity deletes(String nos) {
        boolean b = sysMenuService.removeBatchByIds(Arrays.asList(nos.split(",")));
        return ResponseEntity.ok(ApiResult.ok(b));
    }

    /**
     * 删除
     */
    @GetMapping("/removeById")
    @PreAuthorize("hasAuthority('menu:del')")
    public ResponseEntity removeById(String no) {
        boolean b = sysMenuService.removeById(no);
        return ResponseEntity.ok(ApiResult.ok(b));
    }

    /**
     * 根据 no 修改 状态
     */
    @GetMapping("/updateEnableByNo")
    @PreAuthorize("hasAuthority('menu:edit')")
    public ResponseEntity updateEnableByNo(String no, Boolean enable) {

        UpdateWrapper updateWrapper = new UpdateWrapper();

        updateWrapper.set("enable", enable);
        updateWrapper.eq("no", no);

        boolean update = sysMenuService.update(null, updateWrapper);

        return ResponseEntity.ok(ApiResult.ok(update));
    }

    /**
     * 功能管理 菜单树
     */
    @GetMapping("/getSysMenuListTree")
    public ResponseEntity getSysMenuListTree() {
        List<SysMenuBo> list = sysMenuService.getSysMenuListTree();

        return ResponseEntity.ok(ApiResult.ok(list));
    }

    /**
     * 功能管理  菜单、功能树
     */
    @GetMapping("/getSysMenuListTreeAll")
    public ResponseEntity getSysMenuListTreeAll() {
        List<SysMenuBo> list = sysMenuService.getSysMenuListTreeAll();

        return ResponseEntity.ok(ApiResult.ok(list));
    }
}
